package com.pdg.dungeondelver.configuration;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import org.newdawn.slick.SlickException;
import org.newdawn.slick.util.ResourceLoader;
import org.newdawn.slick.util.xml.XMLElement;
import org.newdawn.slick.util.xml.XMLElementList;
import org.newdawn.slick.util.xml.XMLParser;

public class PropertySerializers {
	private static final String TAG_DEFAULT = "default";
	private Map<String,PropertySerializer> propertySerializers = new HashMap<String,PropertySerializer>();
	private Theme theme;
	private String defaultGenerator;
	public String getDefault(){
		return defaultGenerator;
	}
	public Theme getTheme(){
		return theme;
	}
	public void add(String theType,PropertySerializer theGenerator){
		propertySerializers.put(theType, theGenerator);
	}
	public PropertySerializer get(String theType){
		return propertySerializers.get(theType);
	}
	public PropertySerializers(Theme theTheme,String ref) throws PropertySerializersLoadException{
		theme = theTheme;
		if(!loadFromXml(ref)){
			throw new PropertySerializersLoadException();
		}
	}
	private boolean loadFromXml(String ref) {
		XMLParser parser = new XMLParser();
		XMLElement root;
		try {
			InputStream stream = ResourceLoader.getResourceAsStream(ref);
			root = parser.parse(ref,stream);
			defaultGenerator = root.getAttribute(TAG_DEFAULT);
			XMLElementList children = root.getChildren();
			for(Integer index=0;index<children.size();++index){
				XMLElement child = children.get(index);
				String name = child.getName();
				String className = child.getContent();
				if(defaultGenerator.isEmpty()){
					defaultGenerator = name;
				}
				add(name,(PropertySerializer)Class.forName(className).newInstance());
			}
			return true;
		} catch (SlickException e) {
			e.printStackTrace();
			return false;
		} catch (InstantiationException e) {
			e.printStackTrace();
			return false;
		} catch (IllegalAccessException e) {
			e.printStackTrace();
			return false;
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			return false;
		}
	}
}
